﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CommonTools;
using Newtonsoft.Json.Linq;

namespace shop.Model
{
    public class ServerAddress
    {

        public string DbIp { set; get; }

        public int DbPort { set; get; } = 1433;

        public string FtpAddress { set; get; }


        ///// <summary> 从地址获取数据库的端口 默认1433 </summary>
        //public int GetDbPort()
        //{
        //    if (string.IsNullOrEmpty(this.Address))
        //    {
        //        return 1433;
        //    }

        //    if (this.Address.Contains(","))
        //    {
        //        if (int.TryParse(this.Address.Substring(this.Address.IndexOf(",")+1), out var port))
        //        {
        //            return port;
        //        }

        //    }

        //    return 1433;

        //}



        public static string ConfigFile => "addressHistory.json";



        /// <summary> 所有服务器地址列表 </summary>
        public static List<ServerAddress> GetAll()
        {
            ServerAddress[] servs = new ServerAddress[]
            {
            };

            List<ServerAddress> list = null;
            if (File.Exists(ConfigFile))
            {
                var json = File.ReadAllText(ConfigFile);
                list = JArray.Parse(json).ToObject<List<ServerAddress>>();
            }

            if (list == null)
            {
                list = new List<ServerAddress>();
            }

            //加入固定的几个服务器
            foreach (var serv in servs)
            {
                if (list.Any(a=> a.DbIp== serv.DbIp && a.DbPort == serv.DbPort)== false)
                {
                    list.Add(serv);
                }
            }


            return list;
        }


        /// <summary> 获取当前配置中的服务器 </summary>
        public static ServerAddress GetCurrent()
        {
            var address = IniSet.ReadIniData("server", nameof(DbIp), "");
            var port = IniSet.ReadIniData("server", nameof(DbPort), "").IsNull(0);
            if (string.IsNullOrEmpty(address))
            {
                return null;
            }
            else
            {
                var list = GetAll();
                return list.FirstOrDefault(a => a.DbIp == address && a.DbPort == port);
            }
        }


        /// <summary> 修改当前配置中的服务器 </summary>
        public static void ModifyCurrent(ServerAddress ser)
        {
            if (ser != null)
            {
                IniSet.WriteIniData("server", nameof(DbIp), ser.DbIp);
                IniSet.WriteIniData("server", nameof(DbPort), ser.DbPort.ToString());
            }
        }




    }
}
